package com.kd.juhaowan.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.hjq.http.listener.OnUpdateListener;
import com.hjq.toast.ToastUtils;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.NewsPostApi;
import com.kd.juhaowan.http.api.UploadFileApi;
import com.kd.juhaowan.http.model.FollowResult;
import com.kd.juhaowan.http.model.GameModel;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.http.model.NewsPostModel;
import com.kd.juhaowan.http.model.UploadResult;
import com.kd.juhaowan.ui.adapter.GridImageAdapter;
import com.kd.juhaowan.utils.FullyGridLayoutManager;
import com.kd.juhaowan.utils.GlideEngine;
import com.kd.juhaowan.utils.GlideHelper;
import com.kd.juhaowan.utils.LogUtil;
import com.luck.picture.lib.basic.PictureSelectionModel;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.entity.MediaExtraInfo;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.interfaces.OnQueryFilterListener;
import com.luck.picture.lib.style.BottomNavBarStyle;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.SelectMainStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.luck.picture.lib.utils.DateUtils;
import com.luck.picture.lib.utils.DensityUtil;
import com.luck.picture.lib.utils.MediaUtils;
import com.luck.picture.lib.utils.PictureFileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;
import top.zibin.luban.OnRenameListener;

public class CommentPostActivity extends BaseActivity {





    @BindView(R.id.activity_title)
    TextView titleView;
    @BindView(R.id.recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.item_ratingbar)
    RatingBar ratingBar;
    @BindView(R.id.newspost_edit)
    EditText contentEdit;

private GameModel model;

    @Override
    protected void reInitDate() {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model = (GameModel) getIntent().getSerializableExtra("model");
        titleView.setText("评价《"+model.getName()+"》");
//        setContentView(R.layout.activity_account_login);
        initImageView();
        getStyle();
        launcherPictureResult = createActivityResultLauncher();
    }
private String TAG = "postActivty";
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        int resultCode = result.getResultCode();
                        if (resultCode == RESULT_OK) {
                            ArrayList<LocalMedia> selectList = PictureSelector.obtainSelectorList(result.getData());
                            analyticalSelectResults(selectList);
                        } else if (resultCode == RESULT_CANCELED) {
                            Log.i(TAG, "onActivityResult PictureSelector Cancel");
                        }
                    }
                });
    }

    /**
     * 处理选择结果
     *
     * @param result
     */
    private void analyticalSelectResults(ArrayList<LocalMedia> result) {
        for (LocalMedia media : result) {
            int chooseModel = media.getChooseModel();

            if (media.getWidth() == 0 || media.getHeight() == 0) {
                if (PictureMimeType.isHasImage(media.getMimeType())) {
                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(getBaseContext(), media.getPath());
                    media.setWidth(imageExtraInfo.getWidth());
                    media.setHeight(imageExtraInfo.getHeight());
                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(getBaseContext(), media.getPath());
                    media.setWidth(videoExtraInfo.getWidth());
                    media.setHeight(videoExtraInfo.getHeight());
                }
            }
            Log.i(TAG, "文件名: " + media.getFileName());
            Log.i(TAG, "是否压缩:" + media.isCompressed());
            Log.i(TAG, "压缩:" + media.getCompressPath());
            Log.i(TAG, "初始路径:" + media.getPath());
            Log.i(TAG, "绝对路径:" + media.getRealPath());
            Log.i(TAG, "是否裁剪:" + media.isCut());
            Log.i(TAG, "裁剪路径:" + media.getCutPath());
            Log.i(TAG, "是否开启原图:" + media.isOriginal());
            Log.i(TAG, "原图路径:" + media.getOriginalPath());
            Log.i(TAG, "沙盒路径:" + media.getSandboxPath());
            Log.i(TAG, "水印路径:" + media.getWatermarkPath());
            Log.i(TAG, "视频缩略图:" + media.getVideoThumbnailPath());
            Log.i(TAG, "原始宽高: " + media.getWidth() + "x" + media.getHeight());
            Log.i(TAG, "裁剪宽高: " + media.getCropImageWidth() + "x" + media.getCropImageHeight());
            Log.i(TAG, "文件大小: " + PictureFileUtils.formatAccurateUnitFileSize(media.getSize()));
            Log.i(TAG, "文件时长: " + media.getDuration());
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(result.size()>0){
                    if(result.get(0).getChooseModel()== SelectMimeType.ofImage()){
                        mAdapter.setSelectMax(6);
                    }else {
                        mAdapter.setSelectMax(1);
                    }
                }

                boolean isMaxSize = result.size() == mAdapter.getSelectMax();
                int oldSize = mAdapter.getData().size();
                mAdapter.notifyItemRangeRemoved(0, isMaxSize ? oldSize + 1 : oldSize);
                mAdapter.getData().clear();
                if(result!=null&&result.size()>0){
                    mRecyclerView.setVisibility(View.VISIBLE);
                }else {
                    mRecyclerView.setVisibility(View.GONE);
                }
                mAdapter.getData().addAll(result);
                mAdapter.notifyItemRangeInserted(0, result.size());
            }
        });
    }


    private void getStyle(){

        TitleBarStyle whiteTitleBarStyle = new TitleBarStyle();
        whiteTitleBarStyle.setTitleBackgroundColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_white));
        whiteTitleBarStyle.setTitleDrawableRightResource(R.mipmap.ic_orange_arrow_down);
        whiteTitleBarStyle.setTitleLeftBackResource(com.luck.picture.lib.R.drawable.ps_ic_black_back);
        whiteTitleBarStyle.setTitleTextColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_black));
        whiteTitleBarStyle.setTitleCancelTextColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_53575e));
        whiteTitleBarStyle.setDisplayTitleBarLine(true);

        BottomNavBarStyle whiteBottomNavBarStyle = new BottomNavBarStyle();
        whiteBottomNavBarStyle.setBottomNarBarBackgroundColor(Color.parseColor("#EEEEEE"));
        whiteBottomNavBarStyle.setBottomPreviewSelectTextColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_53575e));

        whiteBottomNavBarStyle.setBottomPreviewNormalTextColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_9b));
        whiteBottomNavBarStyle.setBottomPreviewSelectTextColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_fa632d));
        whiteBottomNavBarStyle.setCompleteCountTips(false);
        whiteBottomNavBarStyle.setBottomEditorTextColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_53575e));
        whiteBottomNavBarStyle.setBottomOriginalTextColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_53575e));

        SelectMainStyle selectMainStyle = new SelectMainStyle();
        selectMainStyle.setStatusBarColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_white));
        selectMainStyle.setDarkStatusBarBlack(true);
        selectMainStyle.setSelectNormalTextColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_9b));
        selectMainStyle.setSelectTextColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_fa632d));
        selectMainStyle.setPreviewSelectBackground(R.drawable.ps_demo_white_preview_selector);
        selectMainStyle.setSelectBackground(com.luck.picture.lib.R.drawable.ps_checkbox_selector);
        selectMainStyle.setSelectText(com.luck.picture.lib.R.string.ps_done_front_num);
        selectMainStyle.setMainListBackgroundColor(ContextCompat.getColor(getBaseContext(), com.luck.picture.lib.R.color.ps_color_white));

        selectorStyle.setTitleBarStyle(whiteTitleBarStyle);
        selectorStyle.setBottomBarStyle(whiteBottomNavBarStyle);
        selectorStyle.setSelectMainStyle(selectMainStyle);
    }
    private GridImageAdapter mAdapter;
    private  List<LocalMedia> mData = new ArrayList<>();
    private void initImageView(){
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this,
                4, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        RecyclerView.ItemAnimator itemAnimator = mRecyclerView.getItemAnimator();
        if (itemAnimator != null) {
            ((SimpleItemAnimator) itemAnimator).setSupportsChangeAnimations(false);
        }
        mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(4,
                DensityUtil.dip2px(this, 4), false));
        mAdapter = new GridImageAdapter(getBaseContext(), mData);
        mAdapter.setSelectMax(6);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                GlideHelper.imagePreview(CommentPostActivity.this,position,mAdapter.getData());
            }

            @Override
            public void openPicture() {
                onImageClick(null);
            }

            @Override
            public void onItemDelete() {
                mData = mAdapter.getData();
//                if(mData!=null&&mData.size()>0){
//                    mRecyclerView.setVisibility(View.VISIBLE);
//                }else {
//                    mRecyclerView.setVisibility(View.GONE);
//                }
            }
        });
    }
    private ActivityResultLauncher<Intent> launcherPictureResult;
    PictureSelectorStyle selectorStyle = new PictureSelectorStyle();
    public void onImageClick(View view){
        if(mData!=null&&mData.size()>0){
            if(mData.get(0).getChooseModel()!= SelectMimeType.ofImage()){
                ToastUtils.show("不能同时选择图片和视频");
                return;
            }
        }
        // 进入相册
        PictureSelectionModel selectionModel = PictureSelector.create(CommentPostActivity.this)
                .openGallery(SelectMimeType.ofImage())
                .setSelectorUIStyle(selectorStyle)

                .setImageEngine(GlideEngine.createGlideEngine())
//                .setVideoPlayerEngine(videoPlayerEngine)
//                .setCropEngine(getCropFileEngine())
                .setCompressEngine(new ImageFileCompressEngine())
//                .setSandboxFileEngine(new MeSandboxFileEngine())
//                .setCameraInterceptListener(getCustomCameraEvent())
//                .setRecordAudioInterceptListener(new MeOnRecordAudioInterceptListener())
//                .setSelectLimitTipsListener(new MeOnSelectLimitTipsListener())
//                .setEditMediaInterceptListener(getCustomEditMediaEvent())
//                .setPermissionDescriptionListener(getPermissionDescriptionListener())
//                .setPreviewInterceptListener(getPreviewInterceptListener())
//                .setPermissionDeniedListener(getPermissionDeniedListener())
//                .setAddBitmapWatermarkListener(getAddBitmapWatermarkListener())
//                .setVideoThumbnailListener(getVideoThumbnailEventListener())
//                .isAutoVideoPlay(cb_auto_video.isChecked())
//                .isLoopAutoVideoPlay(cb_auto_video.isChecked())
//                .isUseSystemVideoPlayer(isUseSystemPlayer)
                .isPageSyncAlbumCount(true)
//                .setCustomLoadingListener(getCustomLoadingListener())
                .setQueryFilterListener(new OnQueryFilterListener() {
                    @Override
                    public boolean onFilter(LocalMedia media) {
                        return false;
                    }
                })
                //.setExtendLoaderEngine(getExtendLoaderEngine())
//                .setInjectLayoutResourceListener(getInjectLayoutResource())
                .setSelectionMode(SelectModeConfig.MULTIPLE )
//                .setLanguage(language)
//                .setQuerySortOrder(cb_query_sort_order.isChecked() ? MediaStore.MediaColumns.DATE_MODIFIED + " ASC" : "")
//                .setOutputCameraDir(chooseMode == SelectMimeType.ofAudio()
//                        ? getSandboxAudioOutputPath() : getSandboxCameraOutputPath())
//                .setOutputAudioDir(chooseMode == SelectMimeType.ofAudio()
//                        ? getSandboxAudioOutputPath() : getSandboxCameraOutputPath())
//                .setQuerySandboxDir(chooseMode == SelectMimeType.ofAudio()
//                        ? getSandboxAudioOutputPath() : getSandboxCameraOutputPath())
//                .isDisplayTimeAxis(cb_time_axis.isChecked())
//                .isOnlyObtainSandboxDir(cb_only_dir.isChecked())
//                .isPageStrategy(cbPage.isChecked())
//                .isOriginalControl(cb_original.isChecked())
//                .isDisplayCamera(cb_isCamera.isChecked())
//                .isOpenClickSound(cb_voice.isChecked())
//                .setSkipCropMimeType(getNotSupportCrop())
//                .isFastSlidingSelect(cb_fast_select.isChecked())
                //.setOutputCameraImageFileName("luck.jpeg")
                //.setOutputCameraVideoFileName("luck.mp4")
//                .isWithSelectVideoImage(cb_WithImageVideo.isChecked())
//                .isPreviewFullScreenMode(cb_preview_full.isChecked())
//                .isVideoPauseResumePlay(cb_video_resume.isChecked())
//                .isPreviewZoomEffect(cb_preview_scale.isChecked())
//                .isPreviewImage(cb_preview_img.isChecked())
//                .isPreviewVideo(cb_preview_video.isChecked())
//                .isPreviewAudio(cb_preview_audio.isChecked())
//                .setGridItemSelectAnimListener(cb_selected_anim.isChecked() ? new OnGridItemSelectAnimListener() {
//
//                    @Override
//                    public void onSelectItemAnim(View view, boolean isSelected) {
//                        AnimatorSet set = new AnimatorSet();
//                        set.playTogether(
//                                ObjectAnimator.ofFloat(view, "scaleX", isSelected ? 1F : 1.12F, isSelected ? 1.12f : 1.0F),
//                                ObjectAnimator.ofFloat(view, "scaleY", isSelected ? 1F : 1.12F, isSelected ? 1.12f : 1.0F)
//                        );
//                        set.setDuration(350);
//                        set.start();
//                    }
//                } : null)
//                .setSelectAnimListener(cb_selected_anim.isChecked() ? new OnSelectAnimListener() {
//
//                    @Override
//                    public long onSelectAnim(View view) {
//                        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.ps_anim_modal_in);
//                        view.startAnimation(animation);
//                        return animation.getDuration();
//                    }
//                } : null)
                //.setQueryOnlyMimeType(PictureMimeType.ofGIF())
//                .isMaxSelectEnabledMask(cbEnabledMask.isChecked())
//                .isDirectReturnSingle(cb_single_back.isChecked())
                .setMaxSelectNum(6)
//                .setMaxVideoSelectNum(maxSelectVideoNum)
//                .setRecyclerAnimationMode(animationMode)
//                .isGif(cb_isGif.isChecked())
                .setSelectedData(mAdapter.getData());
        selectionModel.forResult(launcherPictureResult);
    }


    /**
     * 自定义压缩
     */
    private static class ImageFileCompressEngine implements CompressFileEngine {

        @Override
        public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
            Luban.with(context).load(source).ignoreBy(100).setRenameListener(new OnRenameListener() {
                @Override
                public String rename(String filePath) {
                    int indexOf = filePath.lastIndexOf(".");
                    String postfix = indexOf != -1 ? filePath.substring(indexOf) : ".jpg";
                    return DateUtils.getCreateFileName("CMP_") + postfix;
                }
            }).filter(new CompressionPredicate() {
                @Override
                public boolean apply(String path) {
                    if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) {
                        return true;
                    }
                    return !PictureMimeType.isUrlHasGif(path);
                }
            }).setCompressListener(new OnNewCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(String source, File compressFile) {
                    if (call != null) {
                        call.onCallback(source, compressFile.getAbsolutePath());
                    }
                }

                @Override
                public void onError(String source, Throwable e) {
                    if (call != null) {
                        call.onCallback(source, null);
                    }
                }
            }).launch();
        }
    }

    @OnClick(R.id.post_btn)
    public void onConfirmClick(){
        if(TextUtils.isEmpty(contentEdit.getText().toString().trim())){
            ToastUtils.show("请输入评论内容");
            return;
        }
        if(ratingBar.getRating()<0.5){
            ToastUtils.show("请对游戏进行打星");
            return;
        }


        showLoadingDialog();
        uploadImages();
    }
    private HashMap<LocalMedia,String> imageMap = new HashMap<>();
    private void uploadImages(){
        mData =mAdapter.getData();
//        mData.get(0).getChooseModel()
        if(mData!=null&&mData.size()>0){
            LogUtil.debugLog(mData.size()+"........");
            imageMap.clear();
//            for (LocalMedia media:mData) {
//                    uplaodImage(media);
//            }
            uplaodImage();


        }else{
            uploadVedie();
        }

    }

    private void uplaodImage(){
        EasyHttp.post(this)
                .api(new UploadFileApi(new File(mData.get(imageMap.size()).getRealPath())))
                .request(new OnUpdateListener<HttpData<UploadResult>>() {

                    @Override
                    public void onUpdateProgressChange(int progress) {

                    }

                    @Override
                    public void onUpdateSuccess(HttpData<UploadResult> result) {
                        imageMap.put(mData.get(imageMap.size()),result.getData().getFile_name());
                        if(imageMap.size()==mData.size()){
                            uploadVedie();
                        }else{
                            uplaodImage();
                        }
                    }

                    @Override
                    public void onUpdateFail(Exception e) {
                        cancelLoadingDialog();
                        e.printStackTrace();
                        ToastUtils.show(e.getMessage());
//                        uplaodImage();
                    }


                });
    }

    private void uploadVedie(){
        NewsPostModel postModel =new NewsPostModel();
        String content = contentEdit.getText().toString().trim();
        postModel.setContent(content);
        postModel.setNumber_stars(String.valueOf(ratingBar.getRating()));
        postModel.setGame_id(model.getId());
        if(imageMap.size()>0){
            String tmp="";
            int type=mData.get(0).getChooseModel()== SelectMimeType.ofImage()?1:2;

            for (LocalMedia med:mData) {
                if(imageMap.containsKey(med)){
                    tmp+=imageMap.get(med)+",";
                }
            }
            tmp = tmp.substring(0,tmp.length()-1);

            postModel.setImages(tmp);

        }
        EasyHttp.post(this).api(new NewsPostApi(postModel)).request(new HttpCallbackProxy<HttpData<FollowResult>>(this){
            @Override
            public void onHttpSuccess(HttpData<FollowResult> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                GameDetailActivity2.needRefresh =true;
                ToastUtils.show("发布成功");
                finish();

            }

            @Override
            public void onHttpEnd(Call call) {
                cancelLoadingDialog();
                super.onHttpEnd(call);
            }
        });
    }


    @OnClick(R.id.actvity_back)
    public void onBackClick(){
        finish();
    }
    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.activity_comment_post;
    }

}
